package com.ymatou.operate.trading.api.testcase;

import java.io.IOException;
import java.math.BigDecimal;
import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Random;

import org.json.JSONArray;
import org.junit.After;
import org.junit.AfterClass;
import org.junit.Before;
import org.junit.BeforeClass;
import org.junit.Test;
import org.junit.experimental.categories.Category;

import com.ymatou.iapi.trading.operate.parameter.ActivityVo;
import com.ymatou.iapi.trading.operate.parameter.OrderGroupVo;
import com.ymatou.iapi.trading.operate.parameter.OrderItemVo;
import com.ymatou.iapi.trading.operate.parameter.OrderVo;
import com.ymatou.iapi.trading.operate.parameter.PlaceOrderResp;
import com.ymatou.iapi.trading.operate.parameter.SellerCouponVo;
import com.ymatou.iapi.trading.operate.parameter.YmatouCouponVo;
import com.ymatou.iapi.trading.operate.parameter.enums.ActivityPromotionTypeEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.AppTerminalSourceEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.LogisticsTypeEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.OrderSourceEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.OrderTypeEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.PriceTypeEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.ProductRefundChannelEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.SalesTypeEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.SellerCouponApplianceTypeEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.TerminalSourceEnum;
import com.ymatou.iapi.trading.operate.parameter.enums.YmatouCouponApplianceTypeEnum;
import com.ymatou.iapi.trading.operate.parameter.req.ApplySalesRefundRequestBean;
import com.ymatou.iapi.trading.operate.parameter.req.PlaceOrderReq;
import com.ymatou.iapi.trading.operate.parameter.req.ApproveRefundBillReq;
import com.ymatou.iapi.trading.operate.service.ApplySalesRefundRequestCall;
import com.ymatou.iapi.trading.operate.service.PlaceOrderCall;
import com.ymatou.iapi.trading.operate.service.SalesRefundSuccessRequestCall;
import com.ymatou.operate.trading.api.parameter.AutoConfirmReceiveBean;
import com.ymatou.operate.trading.api.parameter.FrozenOrUnFrozenOrderBean;
import com.ymatou.operate.trading.api.service.AutoConfirmReceiveCall;
import com.ymatou.operate.trading.api.service.FrozenOrUnFrozenOrderCall;
import com.ymt.core.tool.Logger;
import com.ymt.utils.annotation.TestCase;
import com.ymt.utils.annotation.TestSuite;
import com.ymt.utils.tag.P1;
import com.ymt.utils.tag.P3;
import com.ymttest.business.service.CouponCallService;
import com.ymttest.business.service.OrderCallService;
import com.ymttest.business.service.PaymentProxyCallService;
import com.ymttest.business.service.ProductCallService;
import com.ymttest.database.model.YmtCouponPrivateUserBound;
import com.ymttest.database.sqlwapper.DefaultWapper;
import com.ymttest.database.sqlwapper.YmtCouponPrivateUserBoundWapper;
import com.ymttest.utils.EnvSetup;
import com.ymttest.utils.TestDataManager;
import com.ymttest.utils.YMTDateUtil;

/**
 * 买家确认收货 FreeMaker Template自动生成代码
 */
@TestSuite
public class Ts_AutoConfirmReceive {

    private static AutoConfirmReceiveBean confirmreceivebean;
    private static AutoConfirmReceiveCall confirmreceivecall;

    @BeforeClass
    public static void setUp() {
        Logger.createResultFile("自动确认收货");
    }

    @Before
    public void caseUp() {

        confirmreceivebean = new AutoConfirmReceiveBean();
        confirmreceivecall = new AutoConfirmReceiveCall();
    }

    @AfterClass
    public static void tearDown() {
        Logger.generateResult(confirmreceivecall.getOpurl());
    }

    @After
    public void caseDown() {
        Logger.end();
    }

    // 订单投诉维权(冻结和解冻)接口
    private void frozenOrder(boolean isFrozen, int orderId, int sellerId) {
        FrozenOrUnFrozenOrderBean frozenorunfrozenorderBean = new FrozenOrUnFrozenOrderBean();
        FrozenOrUnFrozenOrderCall frozenorunfrozenorderCall = new FrozenOrUnFrozenOrderCall();
        frozenorunfrozenorderBean.setOrderId(orderId);
        frozenorunfrozenorderBean.setUserId(sellerId);
        frozenorunfrozenorderBean.setIsFrozen(isFrozen);
        frozenorunfrozenorderCall.setData(false, frozenorunfrozenorderBean);
        try {
            frozenorunfrozenorderCall.callService();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    // 一个订单下面多个商品
    private Map placeOrder() {
        Map map = new HashMap();
        try {
            PlaceOrderReq placeorderBean = new PlaceOrderReq();
            PlaceOrderCall placeorderCall = new PlaceOrderCall();
            int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
            int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
            // 创建产品
            Logger.comment("前置数据准备");
            HashMap<String, Object> productInfo = ProductCallService
                    .createProduct(sellerId, 3);
            Logger.comment("前置数据准备结束");
            String productId = (String) productInfo.get("productId");
            Logger.debug("productId:" + productId);
            String productName = (String) productInfo.get("productName");
            String pic = (String) productInfo.get("pic");
            BigDecimal price = (BigDecimal) (productInfo.get("price"));
            String catalogId = (String) productInfo.get("catalogId");
            YmatouCouponVo ymtCoupon = new YmatouCouponVo();
            // 平台优惠券
            BigDecimal couponValue = new BigDecimal(13);
            String couponCode = new OrderCallService().receivePlatformCoupon(userId, couponValue);
            ymtCoupon.setApplianceType(YmatouCouponApplianceTypeEnum.ALL);
            ymtCoupon.setCouponCode(couponCode);
            ymtCoupon.setCouponValue(couponValue);
            placeorderBean.setAppId("AutoTest");
            placeorderBean.setYmatouCoupon(ymtCoupon);
            placeorderBean.setUserId(userId);
            placeorderBean.setRequestId(TestDataManager.getRandomUUID()
                    .toString());
            placeorderBean.setTerminalSource(TerminalSourceEnum.IOS);
            placeorderBean.setAppTerminalSource(AppTerminalSourceEnum.Phone);
            placeorderBean.setSourceIp("127.0.0.1");
            placeorderBean.setAppId("ios");
            placeorderBean.setDeviceId("7777777777888888888888999");
            OrderGroupVo groupVo1 = new OrderGroupVo();
            placeorderBean.setOrderSource(OrderSourceEnum.PC);
            // 商家优惠券
            BigDecimal sellerCouponValue = new BigDecimal(15);
            String sellerCouponCode = new CouponCallService().receiveCouponInfo(sellerId, userId,
                    couponValue);
            SellerCouponVo sellerCoupon = new SellerCouponVo();
            sellerCoupon.setApplianceType(SellerCouponApplianceTypeEnum.ALL);
            sellerCoupon.setCouponCode(sellerCouponCode);
            sellerCoupon.setCouponValue(sellerCouponValue);
            groupVo1.setSellerCoupon(sellerCoupon);
            groupVo1.setSellerId(sellerId);
            List<OrderVo> orders = new ArrayList<OrderVo>();
            OrderVo ordervo1 = new OrderVo();
            ordervo1.setAutoCancelOrderHours(new BigDecimal(1));
            ordervo1.setOrderType(OrderTypeEnum.Spot);
            ordervo1.setPaidFull(true);
            ordervo1.setAddress("上海市闸北区灵石路636号");
            ordervo1.setLeaveWord("ymt autotest");
            ordervo1.setPhone("13100000001");
            ordervo1.setPostCode("200001");
            ordervo1.setTelephone("021-51002100");
            ordervo1.setReceiveName("李四");
            List<OrderItemVo> items = new ArrayList<OrderItemVo>();
            OrderItemVo orderitem1 = new OrderItemVo();
            orderitem1.setCatalogId(TestDataManager.getRandomUUID().toString());
            orderitem1.setProductNum(3);
            orderitem1.setProductName(productName);
            orderitem1.setPriceType(PriceTypeEnum.VipPrice);
            orderitem1.setProductId(TestDataManager.getRandomUUID().toString());
            price = new BigDecimal(210);
            orderitem1.setEarnestPrice(price);
            orderitem1.setProductPrice(price);
            orderitem1.setOriginalPrice(price);
            orderitem1.setSalesType(SalesTypeEnum.AlreadyInStock);
            orderitem1.setLogisticsType(LogisticsTypeEnum.SailProtect);
            orderitem1.setProductRefundChannel(ProductRefundChannelEnum.Official);
            orderitem1.setBrandId(5);
            orderitem1.setPackageNo("11111111");
            orderitem1
                    .setProductDetailInfo("e5a1eccf-6a14-458f-b907-35dc9a3d2713#适用人群:b13e9eb1-98d6-4d39-8c35-225758e443d3#男");
            orderitem1.setProductRecordNo("1234567");
            orderitem1.setProductRefundChannel(ProductRefundChannelEnum.Official);
            orderitem1
                    .setProperty("06f25e0c-e431-44ae-8a07-4d0bc824e3bd#尺寸:951a814e-2ded-4241-b9a0-91b2cd9a44fd#6,d2f663ea-3214-4344-abce-a8eaffcc43ce#颜色:f3ed3ad7-a084-450b-b698-256542963306#红色");
            ActivityVo activity = new ActivityVo();
            activity.setActivityId(46870);
            activity.setActivityBeginDate(YMTDateUtil.getBeforeOrNextDay(-10, "yyyy-MM-dd'T'HH:mm:ss"));
            activity.setActivityEndDate(YMTDateUtil.getBeforeOrNextDay(10, "yyyy-MM-dd'T'HH:mm:ss"));
            activity.setActivityTemplateId(12345678);
            activity.setCommissionRate(new BigDecimal(1.1));
            activity.setCost(true);
            activity.setFeeFree(false);
            activity.setPremium(new BigDecimal(1.5));
            activity.setPromotionPrice(new BigDecimal(15));
            activity.setPromotionType(ActivityPromotionTypeEnum.DiscountRate);
            activity.setUseCoupon(true);
            orderitem1.setActivity(activity);
            ordervo1.setOrderItems(items);
            ordervo1.setFreight(new BigDecimal("21"));
            // 第2件商品
            OrderItemVo orderitem2 = new OrderItemVo();
            orderitem2.setCatalogId(TestDataManager.getRandomUUID().toString());
            orderitem2.setProductNum(1);
            orderitem2.setProductName(productName);
            orderitem2.setPriceType(PriceTypeEnum.VipPrice);
            orderitem2.setProductId(TestDataManager.getRandomUUID().toString());
            price = new BigDecimal(270);
            orderitem2.setEarnestPrice(price);
            orderitem2.setProductPrice(price);
            orderitem2.setOriginalPrice(price);
            orderitem2.setSalesType(SalesTypeEnum.AlreadyInStock);
            orderitem2.setLogisticsType(LogisticsTypeEnum.SailProtect);
            orderitem2.setProductRefundChannel(ProductRefundChannelEnum.Official);
            orderitem2.setBrandId(5);
            orderitem2.setPackageNo("11111111");
            orderitem2
                    .setProductDetailInfo("e5a1eccf-6a14-458f-b907-35dc9a3d2713#适用人群:b13e9eb1-98d6-4d39-8c35-225758e443d3#男");
            orderitem2.setProductRecordNo("1234567");
            orderitem2.setProductRefundChannel(ProductRefundChannelEnum.Official);
            orderitem2
                    .setProperty("06f25e0c-e431-44ae-8a07-4d0bc824e3bd#尺寸:951a814e-2ded-4241-b9a0-91b2cd9a44fd#6,d2f663ea-3214-4344-abce-a8eaffcc43ce#颜色:f3ed3ad7-a084-450b-b698-256542963306#红色");
            orderitem2.setActivity(activity);
            items.add(orderitem1);
            items.add(orderitem2);
            ordervo1.setOrderItems(items);
            ordervo1.setFreight(new BigDecimal("21"));
            orders.add(ordervo1);
            groupVo1.setOrders(orders);
            placeorderBean.setOrderGroups(Arrays.asList(groupVo1));
            placeorderCall.setData(false, placeorderBean);
            placeorderCall.callService();
            JSONArray orderIds = placeorderCall.getOrderIds();
            int tradingId = placeorderCall.getTradingId();
            map.put("orderIds", orderIds);
            map.put("tradingId", tradingId);
        } catch (Exception e) {
            Logger.fail(e);
        }
        return map;
    }

    // 创建2个买手多个订单，使用平台优惠券,商家券
    private Map placeOrder3() {
        Map map = new HashMap();
        try {
            PlaceOrderReq placeorderBean = new PlaceOrderReq();
            PlaceOrderCall placeorderCall = new PlaceOrderCall();
            int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
            int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));

            String productName = "auto自动化测试";
            String pic = "http://p243.img.ymatou.com:10243/upload/productdes/3afa103d4ec4466f824b9f0458d6f4e2.jpg";
            BigDecimal price = new BigDecimal(130);
            String productId = "auto123456";
            YmatouCouponVo ymtCoupon = new YmatouCouponVo();
            // 平台优惠券
            BigDecimal couponValue = new BigDecimal(13);
            String couponCode = new OrderCallService().receivePlatformCoupon(userId, couponValue);
            ymtCoupon.setApplianceType(YmatouCouponApplianceTypeEnum.ALL);
            ymtCoupon.setCouponCode(couponCode);
            ymtCoupon.setCouponValue(couponValue);
            placeorderBean.setAppId("AutoTest");
            placeorderBean.setYmatouCoupon(ymtCoupon);
            placeorderBean.setUserId(userId);
            placeorderBean.setRequestId(TestDataManager.getRandomUUID()
                    .toString());
            placeorderBean.setTerminalSource(TerminalSourceEnum.IOS);
            placeorderBean.setAppTerminalSource(AppTerminalSourceEnum.Phone);
            OrderGroupVo groupVo1 = new OrderGroupVo();
            // 商家优惠券
            BigDecimal sellerCouponValue = new BigDecimal(15);
            String sellerCouponCode = new CouponCallService().receiveCouponInfo(sellerId, userId,
                    couponValue);

            SellerCouponVo sellerCoupon = new SellerCouponVo();
            sellerCoupon.setApplianceType(SellerCouponApplianceTypeEnum.ALL);
            sellerCoupon.setCouponCode(sellerCouponCode);
            sellerCoupon.setCouponValue(sellerCouponValue);
            groupVo1.setSellerCoupon(sellerCoupon);
            groupVo1.setSellerId(sellerId);
            List<OrderVo> orders = new ArrayList<OrderVo>();
            OrderVo ordervo1 = new OrderVo();
            ordervo1.setAutoCancelOrderHours(new BigDecimal(1));
            ordervo1.setOrderType(OrderTypeEnum.Spot);
            ordervo1.setPaidFull(true);
            ordervo1.setMerchant(true);

            List<OrderItemVo> items = new ArrayList<OrderItemVo>();
            OrderItemVo orderitem1 = new OrderItemVo();
            orderitem1.setProductNum(1);
            orderitem1.setProductName(productName);
            orderitem1.setPriceType(PriceTypeEnum.VipPrice);
            orderitem1.setProductId(productId);
            orderitem1.setCatalogId(TestDataManager.getRandomUUID().toString());
            price = new BigDecimal(210);
            orderitem1.setEarnestPrice(price);
            orderitem1.setProductPrice(price);
            orderitem1.setOriginalPrice(price);
            orderitem1.setSalesType(SalesTypeEnum.AlreadyInStock);
            orderitem1.setLogisticsType(LogisticsTypeEnum.SailProtect);
            orderitem1.setProductRefundChannel(ProductRefundChannelEnum.Official);
            items.add(orderitem1);
            ordervo1.setOrderItems(items);
            ordervo1.setFreight(new BigDecimal("71"));

            // 第二个订单
            orders.add(ordervo1);
            orders.add(ordervo1);
            orders.add(ordervo1);
            groupVo1.setOrders(orders);

            // 买手2
            OrderGroupVo groupVo2 = new OrderGroupVo();
            // 商家优惠券
            BigDecimal sellerCouponValue2 = new BigDecimal(15);
            String sellerCouponCode2 = new CouponCallService().receiveCouponInfo(sellerId, userId,
                    couponValue);
            SellerCouponVo sellerCoupon2 = new SellerCouponVo();
            sellerCoupon2.setApplianceType(SellerCouponApplianceTypeEnum.ALL);
            sellerCoupon2.setCouponCode(sellerCouponCode2);
            sellerCoupon2.setCouponValue(sellerCouponValue2);
            groupVo2.setSellerCoupon(sellerCoupon2);
            // 卖家2
            int sellerId2 = Integer.valueOf(EnvSetup.getData("BuyerId"));
            groupVo2.setSellerId(sellerId2);
            List<OrderVo> sellerId2orders1 = new ArrayList<OrderVo>();
            OrderVo sellerId2order1 = new OrderVo();
            sellerId2order1.setAutoCancelOrderHours(new BigDecimal(1));
            sellerId2order1.setOrderType(OrderTypeEnum.Spot);
            sellerId2order1.setPaidFull(true);
            // 定义买手下订单列表
            List<OrderItemVo> sellerId2Items1 = new ArrayList<OrderItemVo>();
            // 订单1
            OrderItemVo sellerId2Item1 = new OrderItemVo();

            String catalogId2 = TestDataManager.getRandomUUID().toString();
            sellerId2Item1.setCatalogId(TestDataManager.getRandomUUID().toString());
            // 商品数量
            int productNum2 = 1 + new Random().nextInt(5);
            sellerId2Item1.setProductNum(productNum2);
            sellerId2Item1.setProductName(productName);
            sellerId2Item1.setPriceType(PriceTypeEnum.VipPrice);
            sellerId2Item1.setProductId(productId);
            BigDecimal price2 = new BigDecimal(370);
            sellerId2Item1.setEarnestPrice(price2);
            sellerId2Item1.setProductPrice(price2);
            sellerId2Item1.setOriginalPrice(price2);
            sellerId2Item1.setSalesType(SalesTypeEnum.AlreadyInStock);
            sellerId2Item1.setLogisticsType(LogisticsTypeEnum.SailProtect);
            sellerId2Item1.setProductRefundChannel(ProductRefundChannelEnum.Official);
            sellerId2Items1.add(sellerId2Item1);
            sellerId2order1.setOrderItems(sellerId2Items1);
            sellerId2order1.setFreight(new BigDecimal("45"));
            sellerId2orders1.add(sellerId2order1);
            groupVo2.setOrders(sellerId2orders1);

            List<OrderGroupVo> orderGroupVos = new ArrayList<OrderGroupVo>();
            orderGroupVos.add(groupVo1);
            orderGroupVos.add(groupVo2);

            placeorderBean.setOrderGroups(orderGroupVos);
            placeorderCall.setData(placeorderBean);
            placeorderCall.callService();

            YmtCouponPrivateUserBoundWapper ymtCouponPrivate = new YmtCouponPrivateUserBoundWapper();
            List<YmtCouponPrivateUserBound> listCoupon = ymtCouponPrivate
                    .selectBysCouponCode(couponCode);
            int ymtBeforeCount = listCoupon.get(0).getiCouponUsedCount();
            List<YmtCouponPrivateUserBound> listCoupon2 = ymtCouponPrivate
                    .selectBysCouponCode(sellerCouponCode);
            int sellerBeforeCount = listCoupon2.get(0).getiCouponUsedCount();

            map.put("orderId", placeorderCall.getOrderIds());
            map.put("tradingId", placeorderCall.getTradingId());
            map.put("ymtCouponCode", couponCode);
            map.put("sellerCouponCode1", sellerCouponCode);
            map.put("sellerCouponCode2", sellerCouponCode2);
            map.put("ymtBeforeCount", ymtBeforeCount);
            map.put("sellerBeforeCount", sellerBeforeCount);
        } catch (Exception e) {
            Logger.fail(e);
        }
        return map;
    }


    @Test
    @Category(P1.class)
    @TestCase
    public void Tc_AutoConfirmReceive_001() {
        Logger.start(true, "自动确认收货成功");
        try {
            // 创建订单
            Logger.comment("前置数据准备");
            Map map = placeOrder();
            int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
            int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
            JSONArray orderIds = (JSONArray) map.get("orderIds");
            int tradingId = (Integer) map.get("tradingId");
            int orderId = orderIds.getInt(0);
            OrderCallService orderCallService = new OrderCallService();
            // 应付款全金额
            BigDecimal totalPrice = orderCallService.getNeedPrePayAmountOfCash(orderId);
            // 支付订单
            orderCallService.orderPayRequest(userId, totalPrice, tradingId);
            // 接单
            orderCallService.acceptOrder(orderId, sellerId);
            // 商家发货
            orderCallService.dispatched(orderId, sellerId);
            // 修改发货时间为10天前，使其能自动确认收货
            new DefaultWapper().updateOrderDispathTimeByOrderId(orderId);
            // 冻结时间为当前时间20天前，使其能自动确认收货
            new DefaultWapper().updateOrderFrozenByOrderId(orderId);
            Logger.comment("前置数据准备结束");
            // 确认收货请求
            confirmreceivebean.setOrderId(orderId);
            // 发送请求
            confirmreceivecall.setData(confirmreceivebean);
            confirmreceivecall.callService();
            Logger.verifyEquals("ok", confirmreceivecall.getReturnData(), "验证接口返回");
            // 数据库验证
            DefaultWapper database = new DefaultWapper();
            Logger.verifyEquals(4, database.getTradingStatus(orderId), "验证订单交易状态");
            Logger.verifyEquals(1, database.selectOrderTradingStatusByOrderIdAndTradingStatus(orderId, 4).size(),
                    "验证TradingStatus表中 增加一条订单操作记录");
            // 订单主表
            List<Map> ymtOrders = database.selectOrderByOderId(orderId);
            // 订单结算
            List<Map> settlementList = database.selectYmtSettlementInvoice(orderId);
            // 平台券
            String ymtCouponCode = (String) ymtOrders.get(0).get("sYmtCouponCode");
            // 商家券
            String sellerCouponCode = (String) ymtOrders.get(0).get("sSellerCouponCode");
            Logger.verifyEquals(totalPrice, (BigDecimal) settlementList.get(0).get("CashAmount"), "验证退款金额是否等于付款金额");
            Logger.verifyEquals(2, settlementList.get(0).get("SettlementUser"), "验证SettlementUser 为2");
            Logger.verifyEquals(0, settlementList.get(0).get("SettlementStatus"), "验证SettlementStatus 为1");
            Logger.verifyEquals(1, settlementList.get(0).get("BusinessType"), "验证BusinessType 为1 确认收货订单结算");
            Logger.verifyEquals((BigDecimal) ymtOrders.get(0).get("fYmtCouponAmount"),
                    (BigDecimal) settlementList.get(0).get("CouponAmount"), "验证退款结算单退回的平台CouponAmount");
        } catch (Exception e) {
            Logger.fail(e);
        }
    }

    @Test
    @Category(P3.class)
    @TestCase
    public void Tc_AutoConfirmReceive_002() {
        Logger.start(false, "重复自动确认收货");
        try {
            // 创建订单
            Logger.comment("前置数据准备");
            Map map = placeOrder();
            int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
            int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
            JSONArray orderIds = (JSONArray) map.get("orderIds");
            int tradingId = (Integer) map.get("tradingId");
            int orderId = orderIds.getInt(0);
            OrderCallService orderCallService = new OrderCallService();
            // 应付款全金额
            BigDecimal totalPrice = orderCallService.getNeedPrePayAmountOfCash(orderId);
            // 支付订单
            orderCallService.orderPayRequest(userId, totalPrice, tradingId);
            // 接单
            orderCallService.acceptOrder(orderId, sellerId);
            // 商家发货
            orderCallService.dispatched(orderId, sellerId);
            // 修改发货时间为10天前，使其能自动确认收货
            new DefaultWapper().updateOrderDispathTimeByOrderId(orderId);
            // 冻结时间为当前时间20天前，使其能自动确认收货
            new DefaultWapper().updateOrderFrozenByOrderId(orderId);
            Logger.comment("前置数据准备结束");
            // 确认收货请求
            confirmreceivebean.setOrderId(orderId);
            // 发送请求
            confirmreceivecall.setData(confirmreceivebean);
            confirmreceivecall.callService();
            // 发送请求
            Logger.comment("重复请求");
            confirmreceivecall.callService();
            Logger.verifyEquals("ok", confirmreceivecall.getReturnData(), "验证接口返回");
            // 数据库验证
            DefaultWapper database = new DefaultWapper();
            Logger.verifyEquals(4, database.getTradingStatus(orderId), "验证订单交易状态");
            Logger.verifyEquals(1, database.selectOrderTradingStatusByOrderIdAndTradingStatus(orderId, 4).size(),
                    "验证TradingStatus表中 增加一条订单操作记录");
        } catch (Exception e) {
            Logger.fail(e);
        }
    }

    @Test
    @Category(P3.class)
    @TestCase
    public void Tc_AutoConfirmReceive_003() {
        Logger.start(false, "订单号不存在");
        try {
            int orderId = 1111;
            confirmreceivebean.setOrderId(orderId);
            // 发送请求
            confirmreceivecall.setData(confirmreceivebean);
            confirmreceivecall.callService();
            Logger.verifyEquals("ok", confirmreceivecall.getReturnData(), "验证接口返回");
        } catch (Exception e) {
            Logger.fail(e);
        }
    }

    @Test
    @Category(P3.class)
    @TestCase
    public void Tc_AutoConfirmReceive_004() {
        Logger.start(false, "订单号为null");
        try {
            int orderId = 1111;
            // confirmreceivebean.setOrderId(orderId);
            // 发送请求
            confirmreceivecall.setData(confirmreceivebean);
            confirmreceivecall.callService();
            Logger.verifyEquals("fail", confirmreceivecall.getReturnData(), "验证接口返回");

        } catch (Exception e) {
            Logger.fail(e);
        }
    }

    @Test
    @Category(P1.class)
    @TestCase
    public void Tc_AutoConfirmReceive_005() {
        Logger.start(true, "当前订单为退货退款中,自动确认收货失败");
        try {
            // 创建订单
            Logger.comment("前置数据准备");
            PlaceOrderResp placeOrderResp=new OrderCallService().createM2cOrder();

            int orderId = placeOrderResp.getOrderList().get(0).getOrderId();
            int sellerId =placeOrderResp.getOrderList().get(0).getSellerId();
            int userId =placeOrderResp.getUserId();         
            int tradingId = placeOrderResp.getTradingId();

            BigDecimal totalPrice =  placeOrderResp.getPayAmount();// 支付金额
            OrderCallService orderCallService = new OrderCallService();
            // 支付订单
            orderCallService.orderPayRequest(userId, totalPrice, tradingId);
            // 接单
            orderCallService.acceptOrder(orderId, sellerId);
            // 商家发货
            orderCallService.dispatched(orderId, sellerId);
            // 退款中
            orderCallService.applySalesRefundRequestInJava(orderId);
            Logger.comment("前置数据准备结束");
            // 确认收货请求
            confirmreceivebean.setOrderId(orderId);
            // 发送请求
            confirmreceivecall.setData(confirmreceivebean);
            confirmreceivecall.callService();
            Logger.verifyEquals("fail", confirmreceivecall.getReturnData(), "验证接口返回");
        } catch (Exception e) {
            Logger.fail(e);
        }
    }

    @Test
    @Category(P1.class)
    @TestCase
    public void Tc_AutoConfirmReceive_006() {
        Logger.start(true, "当前订单还未到自动化确认收货时间,自动确认收货失败");
        try {
            // 创建订单
            Logger.comment("前置数据准备");
            PlaceOrderResp placeOrderResp=new OrderCallService().createM2cOrder();

            int orderId = placeOrderResp.getOrderList().get(0).getOrderId();
            int sellerId =placeOrderResp.getOrderList().get(0).getSellerId();
            int userId =placeOrderResp.getUserId();         
            int tradingId = placeOrderResp.getTradingId();

            BigDecimal totalPrice =  placeOrderResp.getPayAmount();// 支付金额
            OrderCallService orderCallService = new OrderCallService();
            // 支付订单
            orderCallService.orderPayRequest(userId, totalPrice, tradingId);
            // 接单
            orderCallService.acceptOrder(orderId, sellerId);
            // 商家发货
            orderCallService.dispatched(orderId, sellerId);
            // 退款中
            orderCallService.applySalesRefundRequestInJava(orderId);
            Logger.comment("前置数据准备结束");
            // 确认收货请求
            confirmreceivebean.setOrderId(orderId);
            // 发送请求
            confirmreceivecall.setData(confirmreceivebean);
            confirmreceivecall.callService();
            Logger.verifyEquals("fail", confirmreceivecall.getReturnData(), "验证接口返回");

        } catch (Exception e) {
            Logger.fail(e);
        }
    }

    @Test
    @Category(P1.class)
    @TestCase
    public void Tc_AutoConfirmReceive_007() {
        Logger.start(true, "当前订单为投诉冻结中，自动确认收货失败");
        try {
            // 创建订单
            Logger.comment("前置数据准备");
            PlaceOrderResp placeOrderResp=new OrderCallService().createM2cOrder();

            int orderId = placeOrderResp.getOrderList().get(0).getOrderId();
            int sellerId =placeOrderResp.getOrderList().get(0).getSellerId();
            int userId =placeOrderResp.getUserId();         
            int tradingId = placeOrderResp.getTradingId();

            BigDecimal totalPrice =  placeOrderResp.getPayAmount();// 支付金额
            OrderCallService orderCallService = new OrderCallService();
            // 支付订单
            orderCallService.orderPayRequest(userId, totalPrice, tradingId);
            // 接单
            orderCallService.acceptOrder(orderId, sellerId);
            // 商家发货
            orderCallService.dispatched(orderId, sellerId);
            // 投诉维权冻结中
            frozenOrder(true, orderId, sellerId);
            Logger.comment("前置数据准备结束");
            // 确认收货请求
            confirmreceivebean.setOrderId(orderId);
            // 发送请求
            confirmreceivecall.setData(confirmreceivebean);
            confirmreceivecall.callService();
            Logger.verifyEquals("fail", confirmreceivecall.getReturnData(), "验证接口返回");

        } catch (Exception e) {
            Logger.fail(e);
        }
    }

    @Test
    @Category(P1.class)
    @TestCase
    public void Tc_AutoConfirmReceive_008() {
        Logger.start(true, "当前订单为投诉解冻,自动确认收货成功");
        try {
            // 创建订单
            Logger.comment("前置数据准备");
            Map map = placeOrder();
            int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
            int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
            JSONArray orderIds = (JSONArray) map.get("orderIds");
            int tradingId = (Integer) map.get("tradingId");
            int orderId = orderIds.getInt(0);
            OrderCallService orderCallService = new OrderCallService();
            // 应付款全金额
            BigDecimal totalPrice = orderCallService.getNeedPrePayAmountOfCash(orderId);
            // 支付订单
            orderCallService.orderPayRequest(userId, totalPrice, tradingId);
            // 接单
            orderCallService.acceptOrder(orderId, sellerId);
            // 商家发货
            orderCallService.dispatched(orderId, sellerId);
            // 投诉维权冻结中
            frozenOrder(false, orderId, sellerId);
            // 修改发货时间为10天前，使其能自动确认收货
            new DefaultWapper().updateOrderDispathTimeByOrderId(orderId);
            // 冻结时间为当前时间20天前，使其能自动确认收货
            new DefaultWapper().updateOrderFrozenByOrderId(orderId);
            Logger.comment("前置数据准备结束");
            // 确认收货请求
            confirmreceivebean.setOrderId(orderId);
            // 发送请求
            confirmreceivecall.setData(confirmreceivebean);
            confirmreceivecall.callService();
            Logger.verifyEquals("ok", confirmreceivecall.getReturnData(), "验证接口返回");
            // 数据库验证
            DefaultWapper database = new DefaultWapper();
            Logger.verifyEquals(4, database.getTradingStatus(orderId), "验证订单交易状态");
            Logger.verifyEquals(1, database.selectOrderTradingStatusByOrderIdAndTradingStatus(orderId, 4).size(),
                    "验证TradingStatus表中 增加一条订单操作记录");
            // 订单主表
            List<Map> ymtOrders = database.selectOrderByOderId(orderId);
            // 订单结算
            List<Map> settlementList = database.selectYmtSettlementInvoice(orderId);
            // 平台券
            String ymtCouponCode = (String) ymtOrders.get(0).get("sYmtCouponCode");
            // 商家券
            String sellerCouponCode = (String) ymtOrders.get(0).get("sSellerCouponCode");

            Logger.verifyEquals(totalPrice, (BigDecimal) settlementList.get(0).get("CashAmount"), "验证退款金额是否等于付款金额");
            Logger.verifyEquals(2, settlementList.get(0).get("SettlementUser"), "验证SettlementUser 为2");
            Logger.verifyEquals(0, settlementList.get(0).get("SettlementStatus"), "验证SettlementStatus 为1");
            Logger.verifyEquals(1, settlementList.get(0).get("BusinessType"), "验证BusinessType 为1 确认收货订单结算");
            Logger.verifyEquals((BigDecimal) ymtOrders.get(0).get("fYmtCouponAmount"),
                    (BigDecimal) settlementList.get(0).get("CouponAmount"), "验证退款结算单退回的平台CouponAmount");
        } catch (Exception e) {
            Logger.fail(e);
        }
    }

    @Test
    @Category(P1.class)
    @TestCase
    public void Tc_AutoConfirmReceive_009() {
        Logger.start(true, "一个主单下面多个不同买手子订单,子订单依次自动确认收货,校验交易结算表");
        try {
            // 创建订单
            Logger.comment("前置数据准备");
            OrderCallService orderCallService = new OrderCallService();
            int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
            int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
            Map map = placeOrder3();
            JSONArray orderIds = (JSONArray) map.get("orderId");
            BigDecimal totalAmount = BigDecimal.ZERO;
            int tradingId = (Integer) map.get("tradingId");
            for (int i = 0; i < orderIds.length(); i++) {
                int orderId = orderIds.getInt(i);
                totalAmount = orderCallService.getPayableAmount(orderId).add(totalAmount);
            }
            // 支付订单
            orderCallService.orderPayRequest(userId, totalAmount, tradingId);
            for (int i = 0; i < orderIds.length(); i++) {
                int orderId = orderIds.getInt(i);
                // 接单
                orderCallService.acceptOrder(orderId, sellerId);
                // 发货
                orderCallService.dispatched(orderId, sellerId);
                // 修改发货时间为10天前，使其能自动确认收货
                new DefaultWapper().updateOrderDispathTimeByOrderId(orderId);
                // 冻结时间为当前时间20天前，使其能自动确认收货
                new DefaultWapper().updateOrderFrozenByOrderId(orderId);
            }
            Logger.comment("前置数据准备结束");
            DefaultWapper database = new DefaultWapper();
            for (int i = 0; i < orderIds.length(); i++) {
                int orderId = orderIds.getInt(i);
                // 确认收货请求
                confirmreceivebean.setOrderId(orderId);
                // 发送请求
                Logger.comment("订单:" + orderId + "确认收货");
                confirmreceivecall.setData(confirmreceivebean);
                confirmreceivecall.callService();
                Thread.sleep(5000);
                Logger.verifyEquals("ok", confirmreceivecall.getReturnData(), "验证接口返回");
                // 订单主表
                List<Map> ymtOrders = database.selectOrderByOderId(orderId);
                // 订单结算
                List<Map> settlementList = database.selectYmtSettlementInvoice(orderId);
                // 付款金额
                BigDecimal totalPrice = orderCallService.getPayableAmount(orderId);
                // 平台券
                String ymtCouponCode = (String) ymtOrders.get(0).get("sYmtCouponCode");
                // 商家券
                String sellerCouponCode = (String) ymtOrders.get(0).get("sSellerCouponCode");

                Logger.verifyEquals(totalPrice, (BigDecimal) settlementList.get(0).get("CashAmount"), "验证退款金额是否等于付款金额");
                Logger.verifyEquals(2, settlementList.get(0).get("SettlementUser"), "验证SettlementUser 为2");
                Logger.verifyEquals(0, settlementList.get(0).get("SettlementStatus"), "验证SettlementStatus 为1");
                Logger.verifyEquals(1, settlementList.get(0).get("BusinessType"), "验证BusinessType 为1 确认收货订单结算");
                Logger.verifyEquals((BigDecimal) ymtOrders.get(0).get("fYmtCouponAmount"),
                        (BigDecimal) settlementList.get(0).get("CouponAmount"), "验证退款结算单退回的平台CouponAmount");
            }
        } catch (Exception e) {
            Logger.fail(e);
        }
    }

    @Test
    @Category(P1.class)
    @TestCase
    public void Tc_AutoConfirmReceive_010() {
        Logger.start(true, "确认收货前,退一部分款,然后自动确认收货,校验结算单");
        try {
            ApproveRefundBillReq salesrefundsuccessrequestBean = new ApproveRefundBillReq();
            SalesRefundSuccessRequestCall salesrefundsuccessrequestCall = new SalesRefundSuccessRequestCall();
            // 创建订单
            Map map = placeOrder();
            int userId = Integer.valueOf(EnvSetup.getData("BuyUserId"));
            int sellerId = Integer.valueOf(EnvSetup.getData("SellerId"));
            JSONArray orderIds = (JSONArray) map.get("orderIds");
            int tradingId = (Integer) map.get("tradingId");
            int orderId = orderIds.getInt(0);
            OrderCallService orderCallService = new OrderCallService();
            // 应付款全金额
            BigDecimal totalPrice = orderCallService.getNeedPrePayAmountOfCash(orderId);
            // 用余额支付金额
            BigDecimal blanceAmout = new BigDecimal(32);
            // 支付订单 余额+支付宝组合支付
            // 13 为 app国际支付宝，15 微信
            String payType = "13";
            int thirdTradingId = new OrderCallService().orderPayRequest(userId, blanceAmout, tradingId, payType);
            // 支付网关支付回调交易
            PaymentProxyCallService.notifyCall(payType, String.valueOf(thirdTradingId),
                    totalPrice.subtract(blanceAmout).toString()
                    , userId);
            // 等待支付网关异步处理
            Thread.sleep(10000);
            // 卖家接单
            orderCallService.acceptOrder(orderId, sellerId);
            // 发货
            orderCallService.dispatched(orderId, sellerId);
            // 修改发货时间为10天前，使其能自动确认收货
            new DefaultWapper().updateOrderDispathTimeByOrderId(orderId);
            // 冻结时间为当前时间20天前，使其能自动确认收货
            new DefaultWapper().updateOrderFrozenByOrderId(orderId);
            BigDecimal applyRefundAmout = new BigDecimal(130);
            // 申请退款
            ApplySalesRefundRequestBean applysalesrefundrequestBean =
                    orderCallService.applySalesRefundRequestInJavaBean(orderId);
            applysalesrefundrequestBean.getSalesRefundInfoList().get(0).setRefundAmount(applyRefundAmout);
            ApplySalesRefundRequestCall applysalesrefundrequestCall = new ApplySalesRefundRequestCall();

            applysalesrefundrequestCall.setData(false, applysalesrefundrequestBean);
            applysalesrefundrequestCall.callService();
            String refundBillNo = applysalesrefundrequestBean.getSalesRefundInfoList().get(0).getRefundBillNo();
            // 退款处理
            salesrefundsuccessrequestBean.setOperatorInfo("autotest");
            salesrefundsuccessrequestBean.setOrderId(orderId);
            salesrefundsuccessrequestBean.setRefundBillNo("YMTTK0" + orderId);
            salesrefundsuccessrequestCall.setData(false, salesrefundsuccessrequestBean);
            salesrefundsuccessrequestCall.callService();
            // 确认收货请求
            confirmreceivebean.setOrderId(orderId);
            // 发送请求
            confirmreceivecall.setData(confirmreceivebean);
            confirmreceivecall.callService();
            Logger.verifyEquals("ok", confirmreceivecall.getReturnData(), "验证接口返回");
            DefaultWapper defaultWapper = new DefaultWapper();
            // 数据库验
            // 查询交易退款结算表
            List<Map> settlementInvoiceList = defaultWapper.selectYmtSettlementInvoice(orderId);
            // 订单商品表
            List<Map> orderInfoList = defaultWapper.selectOrderInfoByOderId(orderId);
            // 订单主表
            List<Map> ymtOrders = defaultWapper.selectOrderByOderId(orderId);
            // ymtOrderState 表
            List<Map> ymtOrderState = defaultWapper.selectOrderStateByOderId(orderId);
            // 计算退款按比例退的平台优惠券
            BigDecimal productYmtCouponValue =
                    applyRefundAmout.multiply((BigDecimal) ymtOrders.get(0).get("fYmtCouponAmount")).divide(
                            (BigDecimal) ymtOrders.get(0).get("fPayableAmount"),
                            2,
                            BigDecimal.ROUND_DOWN);
            Logger.comment("校验ymt_orders表");
            Logger.verifyEquals(4, (Integer) ymtOrders.get(0).get("iTradingStatus"), "验证iTradingStatus");
            Logger.verifyEquals(10, (Integer) ymtOrders.get(0).get("iSalesRefundStatus"), "验证iSalesRefundStatus");
            Logger.comment("校验ymt_orderstate表");
            Logger.verifyEquals(
                    settlementInvoiceList.stream().filter(account -> (Integer) account.get("BusinessType") == 2)
                            .map(account -> (BigDecimal) account.get("CashAmount"))
                            .reduce(BigDecimal.ZERO, BigDecimal::add), (BigDecimal) ymtOrderState.get(0)
                            .get("fRefundedAmountOfCash"),
                    "验证fRefundedAmountOfCash");
            Logger.verifyEquals(
                    settlementInvoiceList.stream().filter(account -> (Integer) account.get("BusinessType") == 2)
                            .map(account -> (BigDecimal) account.get("fAccountAmount"))
                            .reduce(BigDecimal.ZERO, BigDecimal::add), ymtOrderState.get(0)
                            .get("fRefundedAmountToAccount"),
                    "验证fRefundedAmountToAccount");
            Logger.verifyEquals(
                    settlementInvoiceList.stream().filter(account -> (Integer) account.get("BusinessType") == 2)
                            .map(account -> (BigDecimal) account.get("fThirdPartyAmount"))
                            .reduce(BigDecimal.ZERO, BigDecimal::add), (BigDecimal) ymtOrderState.get(0)
                            .get("fRefundedPaidAmountToThirdParty"),
                    "验证fRefundedPaidAmountToThirdParty");

            Logger.verifyEquals(
                    settlementInvoiceList.stream().filter(account -> (Integer) account.get("BusinessType") == 1)
                            .map(account -> (BigDecimal) account.get("CashAmount"))
                            .reduce(BigDecimal.ZERO, BigDecimal::add), ((BigDecimal) ymtOrderState.get(0)
                            .get("fPaidAmountOfCash")).subtract((BigDecimal) ymtOrderState.get(0)
                            .get("fRefundedAmountOfCash")),
                    "验证确认收货后结算给商家的金额");
        } catch (Exception e) {
            Logger.fail(e);
        }
    }


}
